package com.web.controller.web;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.web.dao.*;
import com.web.domain.WebResponse;
import com.web.domain.dataTable.BootstrapTableColumns;
import com.web.domain.dataTable.BootstrapTableResponse;
import com.web.dto.StoreApplyDto;
import com.web.entity.*;
import com.web.manager.FileUpLoadManager;
import com.web.manager.jpush.SendJPushMessage;
import com.xkk.utils.UUIDUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author FDjavaone
 * @date 2017/9/22
 */
@Slf4j
@Controller
public class WebStoreController {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreApplyMapper storeApplyMapper;
    @Autowired
    private StoreChangeMapper storeChangeMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private FileUpLoadManager fileUpLoadManager;
    @Autowired
    private KftApplyMapper kftApplyMapper;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;


    @RequestMapping(value = "sysu/store",
            method = RequestMethod.GET)
    public String store(Model model, HttpServletRequest request) {
        return "store";
    }

    @RequestMapping(value = "sysu/storeApply",
            method = RequestMethod.GET)
    public String storeApply(Model model, HttpServletRequest request) {
        return "storeApply";
    }


    @RequestMapping(value = "sysu/storeChangeApply",
            method = RequestMethod.GET)
    public String storeChange(Model model, HttpServletRequest request) {
        return "storeChange";
    }


    @RequestMapping(value = "sysu/storeKftApply",
            method = RequestMethod.GET)
    public String storeKftApply(Model model, HttpServletRequest request) {
        return "storeKftApply";
    }

    @Data
    public static class StoreColumns extends BootstrapTableColumns {
        private Long id;
        private Long mId;
        private String type;
        private String merchantName;
        private String level;
        private String licenceNo;
        private String contactor;
        private String contactPhone;
        private String contactTel;
        private String province;
        private String city;
        private String region;
        private Integer businessStatus;
        private Date createTime;
        private Date modifyTime;
        private String storeType;
    }


    @GetMapping("/sysu/getStores")
    @ResponseBody
    public BootstrapTableResponse getStores(StoreColumns storeColumns) {
        if (storeColumns.getMerchantName() != null && !"".equals(storeColumns.getMerchantName())) {
            storeColumns.setMerchantName("%" + storeColumns.getMerchantName() + "%");
        }
        PageHelper.startPage(storeColumns.getPageNumber(), storeColumns.getPageSize());
        Page<Store> page = storeMapper.selectAllStore(storeColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }

    @GetMapping("/sysu/findStore")
    @ResponseBody
    public WebResponse findStore(StoreColumns storeColumns) {
        if (storeColumns.getMerchantName() != null && !"".equals(storeColumns.getMerchantName())) {
            storeColumns.setMerchantName("%" + storeColumns.getMerchantName() + "%");
        }
        List<Store> page = storeMapper.selectAllStoreByName(storeColumns);
        return WebResponse.ok("查询成功", page);
    }


    @Data
    public static class StoreApplyColumns extends BootstrapTableColumns {
        private Long id;
        private Long mId;
        private String type;
        private String merchantName;
        private String level;
        private String licenceNo;
        private String contactor;
        private String contactPhone;
        private String contactTel;
        private String province;
        private String city;
        private String region;
        private Integer status;
        private String storeType;
    }


    @GetMapping("/sysu/getStoreApply")
    @ResponseBody
    public BootstrapTableResponse getStoreApply(StoreApplyColumns storeApplyColumns) {

        PageHelper.startPage(storeApplyColumns.getPageNumber(), storeApplyColumns.getPageSize());
        Page<StoreApply> page = storeApplyMapper.selectAllStoreApply(storeApplyColumns);

        for (StoreApply storeApply : page.getResult()) {
            //店铺持有者
            Member member = memberMapper.selectByPrimaryKey(storeApply.getmId());
            if (member != null) {
                if (member.getInvitedCode() != null && !"".equals(member.getInvitedCode())) {
                    //推荐人
                    Member invited = memberMapper.selectMyUp(member.getInvitedCode());
                    storeApply.setInvited(invited.getName() + "[" + invited.getPhone() + "]");
                }
                storeApply.setRegister(member.getName() + "[" + member.getPhone() + "]");
            }


        }

        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @GetMapping("/sysu/getStoreChange")
    @ResponseBody
    public BootstrapTableResponse getStoreChange(StoreApplyColumns storeApplyColumns) {

        PageHelper.startPage(storeApplyColumns.getPageNumber(), storeApplyColumns.getPageSize());
        Page<StoreChange> page = storeChangeMapper.selectAllStoreChangeApply(storeApplyColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @GetMapping("/sysu/getStoreKft")
    @ResponseBody
    public BootstrapTableResponse getStoreKft(StoreColumns storeColumns) {
        if (storeColumns.getMerchantName() != null && !"".equals(storeColumns.getMerchantName())) {
            storeColumns.setMerchantName("%" + storeColumns.getMerchantName() + "%");
        }
        PageHelper.startPage(storeColumns.getPageNumber(), storeColumns.getPageSize());
        Page<StoreApplyDto> page = storeMapper.selectAllKftAbout(storeColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @RequestMapping("/sysu/storeApply/refuse")
    @ResponseBody
    public WebResponse refuse(StoreApply storeApply) {
        Date date = new Date();
        StoreApply old = storeApplyMapper.selectByPrimaryKey(storeApply.getId());

        if (old.getStatus() == 0) {
            storeApply.setStatus(2);
            storeApply.setModifyTime(date);
            storeApplyMapper.updateByPrimaryKeySelective(storeApply);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("申请审核结果");
            message.setContent("您好，您的店铺（企业）申请被拒，原因：" + storeApply.getReason());
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);

            return WebResponse.ok("操作成功");
        } else {
            return WebResponse.fail("操作失败");
        }
    }

    @RequestMapping("/sysu/store/close")
    @ResponseBody
    public WebResponse storeClose(StoreApply storeApply) {
        Date date = new Date();
        Store old = storeMapper.selectByPrimaryKey(storeApply.getId());
        if (old != null) {
            Store store = new Store();
            store.setBusinessStatus(2);
            store.setId(storeApply.getId());
            store.setModifyTime(date);
            storeMapper.updateByPrimaryKeySelective(store);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("店铺关停通知");
            message.setContent("您好，您的店铺（企业）被管理员关停，原因：" + storeApply.getReason() + "，如有疑问请联系客服，给您带来不便，敬请谅解！");
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);
            stringRedisTemplate.opsForValue().set("store:" + old.getId(), old.getBusinessStatus().toString());
            return WebResponse.ok("操作成功");
        } else {
            return WebResponse.fail("操作失败");
        }
    }

    @RequestMapping("/sysu/store/recovery")
    @ResponseBody
    public WebResponse storeRecovery(StoreApply storeApply) {
        Date date = new Date();
        Store old = storeMapper.selectByPrimaryKey(storeApply.getId());
        if (old != null) {
            Store store = new Store();
            store.setBusinessStatus(Integer.valueOf(stringRedisTemplate.opsForValue().get("store:" + old.getId())));
            store.setId(storeApply.getId());
            store.setModifyTime(date);
            storeMapper.updateByPrimaryKeySelective(store);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("店铺回复营业通知");
            message.setContent("您好，您的店铺（企业）被管理员恢复营业，恢复原因：" + storeApply.getReason() + "，如有疑问请联系客服，给您带来不便，敬请谅解！");
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);

            SendJPushMessage.jPushByMessage(message);
            return WebResponse.ok("操作成功");
        } else {
            return WebResponse.fail("操作失败");
        }
    }

    @GetMapping("/sysu/getStore/detail")
    @ResponseBody
    public BootstrapTableResponse getGoodList(Store store) {
        //PageHelper.startPage(ceremonyJoinColumns.getPageNumber(), ceremonyJoinColumns.getPageSize());
        Page<Store> page = storeMapper.selectById(store.getId());
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @RequestMapping("/sysu/store/del")
    @ResponseBody
    public WebResponse storeDel(StoreApply storeApply) {
        Date date = new Date();
        Store old = storeMapper.selectByPrimaryKey(storeApply.getId());
        if (old != null) {
            Store store = new Store();
            store.setBusinessStatus(3);
            store.setId(storeApply.getId());
            store.setModifyTime(date);
            storeMapper.updateByPrimaryKeySelective(store);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("店铺回复营业通知");
            message.setContent("您好，您的店铺（企业）被管理员删除，删除原因：" + storeApply.getReason() + "，如有疑问请联系客服，给您带来不便，敬请谅解！");
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);
            return WebResponse.ok("操作成功");
        } else {
            return WebResponse.fail("操作失败");
        }
    }

    @RequestMapping("/sysu/storeChange/refuse")
    @ResponseBody
    public WebResponse storeChangeRefuse(StoreChange storeChange) {
        Date date = new Date();
        StoreChange old = storeChangeMapper.selectByPrimaryKey(storeChange.getId());
        if (old.getStatus() == 0) {
            storeChange.setStatus(2);
            storeChange.setModifyTime(date);
            storeChangeMapper.updateByPrimaryKeySelective(storeChange);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("申请审核结果");
            message.setContent("您好，您的店铺（企业）信息变更申请被拒，原因：" + storeChange.getRefuseReason());
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);
            return WebResponse.ok("操作成功");
        } else {
            return WebResponse.fail("操作失败");
        }
    }


    @RequestMapping("/sysu/storeApply/pass")
    @ResponseBody
    public WebResponse pass(StoreApply storeApply) {
        Date date = new Date();
        StoreApply old = storeApplyMapper.selectByPrimaryKey(storeApply.getId());
        if (old.getStatus() == 0) {
            //通过审核创建新的店铺
            Store store = new Store();

            store.setmId(old.getmId());
            store.setType(old.getType());
            store.setMerchantName(old.getMerchantName());
            store.setLat(Double.parseDouble(old.getLoc().split(",")[1]));
            store.setModifyTime(date);

            store.setCity(old.getCity());
            store.setContactor(old.getContactor());
            store.setContactPhone(old.getContactPhone());
            store.setContactTel(old.getContactTel());
            store.setCreateTime(date);
            store.setLicenceImg(old.getLicenceImg());
            store.setIdentityAImg(old.getIdentityAImg());
            store.setIdentityBImg(old.getIdentityBImg());
            store.setStoreImg(old.getStoreImg());
            store.setLevel(old.getLevel());
            store.setLicenceNo(old.getLicenceNo());
            store.setLng(Double.parseDouble(old.getLoc().split(",")[0]));
            store.setProvince(old.getProvince());
            store.setRegion(old.getRegion());
            if (old.getStreet() != null) {
                store.setStreet(old.getStreet());
            }
            if (old.getAddress() != null) {
                store.setAddress(old.getAddress());
            }
            storeMapper.insertSelective(store);

            storeApply.setStatus(1);
            storeApply.setModifyTime(date);
            storeApplyMapper.updateByPrimaryKeySelective(storeApply);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("申请审核结果");
            message.setContent("恭喜您！您的店铺（企业）申请已经通过，快去丰富自己店铺的内容吧。");
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);
            return WebResponse.ok("");
        } else {
            return WebResponse.fail(WebResponse.UF);
        }
    }

    @RequestMapping("/sysu/storeChange/pass")
    @ResponseBody
    public WebResponse storeChange(StoreChange storeChange) {
        Date date = new Date();
        StoreChange old = storeChangeMapper.selectByPrimaryKey(storeChange.getId());
        if (old.getStatus() == 0) {
            //通过审核    获取老店铺的信息
            Store store = storeMapper.selectByPrimaryKey(old.getsId());
            BeanUtils.copyProperties(old, store);
            store.setModifyTime(date);
            store.setId(old.getsId());
            storeMapper.updateByPrimaryKeySelective(store);

            old.setStatus(1);
            old.setModifyTime(date);
            storeChangeMapper.updateByPrimaryKeySelective(old);

            Message message = new Message();
            message.setTargetName("");
            message.setTarget(old.getmId());
            message.setFromName("系统");
            message.setFrom(0L);
            message.setTitle("申请审核结果");
            message.setContent("恭喜您！您的店铺（企业）信息变更申请已经通过。");
            message.setCreateTime(date);
            message.setModifyTime(date);
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);
            return WebResponse.ok("");
        } else {
            return WebResponse.fail(WebResponse.UF);
        }
    }


    @RequestMapping(value = "/sysu/storeKftApplyEdit")
    @ResponseBody
    public WebResponse storeKftApplyEdit(@RequestParam("id") Long id
            ,@RequestParam("licenceNo") String licenceNo
            ,@RequestParam("idValidDate") String idValidDate
            ,@RequestParam("licenceValidDate") String licenceValidDate
            ,@RequestParam("idCardHold") MultipartFile idCardHold
            ,@RequestParam("bankOpen") MultipartFile bankOpen
            ,@RequestParam("bankCardFront") MultipartFile bankCardFront
            ,@RequestParam("bankCardBack") MultipartFile bankCardBack
            ,@RequestParam("storeFront") MultipartFile storeFront) {
        try {
            Store store = storeMapper.selectByPrimaryKey(id);
            KftApply kftApply = kftApplyMapper.findByMid(store.getmId());
            boolean flag = false;
            if (kftApply != null) {
                flag = true;
            }
            KftApply bak = new KftApply();
            bak.setmId(store.getmId());

            InputStream idCardHoldIs = idCardHold.getInputStream();
            String idCardHoldStr = "http://" + fileUpLoadManager.upload(idCardHoldIs, UUIDUtil.getUUID() + bankOpen.getOriginalFilename());

            InputStream bankOpenIs = bankOpen.getInputStream();
            String bankOpenStr = "http://" + fileUpLoadManager.upload(bankOpenIs, UUIDUtil.getUUID() + bankOpen.getOriginalFilename());

            InputStream bankCardFrontIs = bankCardFront.getInputStream();
            String bankCardFrontStr = "http://" + fileUpLoadManager.upload(bankCardFrontIs, UUIDUtil.getUUID() + bankCardFront.getOriginalFilename());

            InputStream bankCardBackIs = bankCardBack.getInputStream();
            String bankCardBackStr = "http://" + fileUpLoadManager.upload(bankCardBackIs, UUIDUtil.getUUID() + bankCardBack.getOriginalFilename());

            InputStream storeFrontIs = storeFront.getInputStream();
            String storeFrontStr = "http://" + fileUpLoadManager.upload(storeFrontIs, UUIDUtil.getUUID() + storeFront.getOriginalFilename());

            if (flag) {
                kftApply.setIdCardHold(idCardHoldStr);
                kftApply.setBankOpen(bankOpenStr);
                kftApply.setBankCardFront(bankCardFrontStr);
                kftApply.setBankCardBack(bankCardBackStr);
                kftApply.setStoreFront(storeFrontStr);
                kftApply.setStatus(1);
                kftApply.setIdValidDate(idValidDate);
                kftApply.setLicenceValidDate(licenceValidDate);
                kftApplyMapper.updateByPrimaryKeySelective(kftApply);
            } else {
                bak.setIdCardHold(idCardHoldStr);
                bak.setBankOpen(bankOpenStr);
                bak.setBankCardFront(bankCardFrontStr);
                bak.setBankCardBack(bankCardBackStr);
                bak.setStoreFront(storeFrontStr);
                bak.setIdValidDate(idValidDate);
                bak.setLicenceValidDate(licenceValidDate);
                kftApplyMapper.insertSelective(bak);
            }
            store.setLicenceNo(licenceNo);
            storeMapper.updateByPrimaryKeySelective(store);
            return WebResponse.ok("补充成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.fail(WebResponse.CF);
        }
    }


}
